package com.ceiling.service;

import com.ceiling.bean.Storage;
import com.ceiling.bean.promotion.*;
import com.ceiling.bean.promotion.ads.bo.AdsCreateBO;
import com.ceiling.bean.promotion.ads.bo.AdsDelBO;
import com.ceiling.bean.promotion.ads.bo.AdsEditBO;
import com.ceiling.bean.promotion.ads.bo.AdsShowListBO;
import com.ceiling.bean.promotion.ads.vo.AdsCreatedByAddPicVO;
import com.ceiling.bean.promotion.ads.vo.AdsCreatedVO;
import com.ceiling.bean.promotion.ads.vo.AdsShowListVO;
import com.ceiling.bean.promotion.ads.vo.AdsUltimateShowListVO;
import com.ceiling.bean.promotion.coup.bo.CoupShowListBO;
import com.ceiling.bean.promotion.coup.vo.CoupUltimateShowListVO;
import com.ceiling.dao.AdMapper;
import com.ceiling.dao.CoupMapper;
import com.ceiling.dao.StorageMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class PromotionServiceImp implements PromotionService {

    @Autowired
    AdMapper adMapper;

    @Autowired
    StorageMapper storageMapper;

    @Autowired
    CoupMapper coupMapper;

/*----------------------------广告管理-------------------------------------*/
    /**
     * 分页+检索广告
     *
     * @param adsShowListBO
     * @return 仅分页的数据
     */
    @Override
    public AdsUltimateShowListVO adShowList(AdsShowListBO adsShowListBO) {

        //设置分页大小
        PageHelper.startPage(adsShowListBO.getPage(), adsShowListBO.getLimit());

        //设置查询排序参数
        AdExample adExample = new AdExample();
        adExample.setOrderByClause(adsShowListBO.getSort() + " " + adsShowListBO.getOrder());

        AdExample.Criteria criteria = adExample.createCriteria();
        if(adsShowListBO.getContent()!=null && !"".equals(adsShowListBO.getContent())){
            criteria.andContentLike("%"+adsShowListBO.getContent()+"%");
        }
        if(adsShowListBO.getName()!=null && !"".equals(adsShowListBO.getName())){
            criteria.andNameLike("%"+adsShowListBO.getName()+"%");
        }



        //设置enable以及delete
//        criteria.andEnabledEqualTo(Boolean.TRUE);

        //todo：应该要显示enable
        criteria.andDeletedEqualTo(Boolean.FALSE);

        //执行sql语句
        List<Ad> ads = adMapper.selectByExample(adExample);

        //获取查询总数
        PageInfo<Ad> pageInfo = new PageInfo<>(ads);
        Integer size = pageInfo.getSize();

        //以下为封装结果
        AdsUltimateShowListVO adsUltimateShowListVO = new AdsUltimateShowListVO();
        List<AdsShowListVO> voArrayList = new ArrayList<AdsShowListVO>();

        //查询结果转换类型
        if (ads != null || ads.size() == 0) {
            for (Ad ad : ads) {
                AdsShowListVO vo = new AdsShowListVO(ad.getId(), ad.getName(), ad.getLink(), ad.getUrl()
                        , ad.getPosition(), ad.getContent(), ad.getEnabled(), ad.getAddTime()
                        , ad.getUpdateTime(), ad.getDeleted());
                voArrayList.add(vo);
            }
        }

        //封装进入最终结果类
        adsUltimateShowListVO.setTotal(size);
        adsUltimateShowListVO.setItems(voArrayList);


        return adsUltimateShowListVO;
    }

    /**
     * 保存文件并返回文件信息
     *
     * @param file,url
     * @return 存储的图片信息
     * 由于数据库和文件传输之间存在事务关系
     */
    @Override
    public AdsCreatedByAddPicVO adCreatePic(MultipartFile file, String url) {


        //获取存储数据
        String uuid = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        String keyName = uuid + "-" + fileName;
        url = url + "/wx/storage/fetch/" + keyName;

        Date date = new Date();
        Integer size = (int) file.getSize();
        String contentType = file.getContentType();


        //转换数据类型
        Storage storage = new Storage(null, keyName,
                fileName, contentType, size, url, date, date, false);

        int affectRows = storageMapper.insertSelective(storage);

        AdsCreatedByAddPicVO addPicVO = null;
        if (affectRows != 0) {
            addPicVO = new AdsCreatedByAddPicVO(storage.getId(), storage.getKey(),
                    storage.getName(), storage.getType(), storage.getSize(),
                    storage.getUrl(), storage.getAddTime(), storage.getUpdateTime());

            // 文件存储(存储在target上)
            String path = PromotionServiceImp.class.getClassLoader().getResource("").getPath();

            //todo:修改可能产生问题
            File outputFile = new File(path + "/picture/" + keyName);


            try {
                file.transferTo(outputFile);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("可能是文件存在才可以传！");

                //修改数据库和文件的传输做一个同步处理
                storageMapper.deleteByPrimaryKey(storage.getId());

                addPicVO = null;
            }
        }
        return addPicVO;
    }

    /**
     * 返回刚添加的广告信息
     *
     * @param adsCreateBO
     * @return 一条广告信息
     */
    @Override
    public AdsCreatedVO adCreated(AdsCreateBO adsCreateBO) {

        Ad ad = new Ad();
        ad.setContent(adsCreateBO.getContent());
        ad.setEnabled(adsCreateBO.getEnabled());
        ad.setName(adsCreateBO.getName());
        ad.setPosition(adsCreateBO.getPosition());
        ad.setUrl(adsCreateBO.getUrl());

        //获取当前时间--（这一部分是自己设置
        Date date = new Date();
        ad.setAddTime(date);
        //todo:这个地方可能需要进行置空
        ad.setUpdateTime(date);



        Integer affectRow = adMapper.insertSelective(ad);

        AdsCreatedVO adsCreatedVO = null;

        if (affectRow != 0) {
            adsCreatedVO = new AdsCreatedVO(ad.getId(), ad.getName(),
                    ad.getUrl(), ad.getPosition(),
                    ad.getContent(), ad.getEnabled(),
                    ad.getAddTime(), ad.getUpdateTime());
        }
        return adsCreatedVO;
    }

    /**
     * 更据提交的内容是否相同进行修改内容
     * @param adsEditBO
     * @return
     */
    @Override
    public AdsCreatedVO adEdit(AdsEditBO adsEditBO) {


        //查看内容是否为变更-变更才需要做出改变-时间的改变
        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();
        criteria.andContentEqualTo(adsEditBO.getContent())
                .andEnabledEqualTo(adsEditBO.getEnabled())
                .andLinkEqualTo(adsEditBO.getLink()).andNameEqualTo(adsEditBO.getName())
                .andPositionEqualTo(adsEditBO.getPosition())
                .andUrlEqualTo(adsEditBO.getUrl()).andIdEqualTo(adsEditBO.getId());

        List<Ad> ads = adMapper.selectByExample(adExample);

        //当没有查到数据时说明数据已经修改，执行修改日期
        AdsCreatedVO adsCreatedVO=null;
        if (ads.size()==0){
            Ad ad = new Ad(adsEditBO.getId(), adsEditBO.getName(),
                    adsEditBO.getLink(), adsEditBO.getUrl(),
                    adsEditBO.getPosition(), adsEditBO.getContent(),
                    null, null, adsEditBO.getEnabled(),
                    adsEditBO.getAddTime(), new Date(),
                    adsEditBO.getDeleted());

            Integer affectRows = adMapper.updateByPrimaryKey(ad);

            if (affectRows != 0) {
                adsCreatedVO = new AdsCreatedVO(ad.getId(),
                        ad.getName(), ad.getUrl(),
                        ad.getPosition(), ad.getContent(),
                        ad.getEnabled(), ad.getAddTime(),
                        ad.getUpdateTime());
            }
        }

        return adsCreatedVO;
    }

    /**
     * 修改enable以及deletet为0，1
     * @param adsDelBO
     * @return
     */
    @Override
    public Integer adDel(AdsDelBO adsDelBO) {
        Ad ad = new Ad();
        ad.setEnabled(Boolean.FALSE);
        ad.setDeleted(Boolean.TRUE);

        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();
        criteria.andIdEqualTo(adsDelBO.getId());

        Integer affectRows = adMapper.updateByExampleSelective(ad, adExample);

        return affectRows;
    }





    /*----------------------------优惠卷管理-------------------------------------*/

    //展示优惠卷信息
    @Override
    public CoupUltimateShowListVO coupShowList(CoupShowListBO coupShowListBO) {
        //设置分页大小
        PageHelper.startPage(coupShowListBO.getPage(), coupShowListBO.getLimit());

        //设置查询排序参数
        CoupExample coupExample = new CoupExample();
        coupExample.setOrderByClause(coupShowListBO.getSort() + " " + coupShowListBO.getOrder());

        //todo：配置优惠卷的查询条件
        CoupExample.Criteria criteria = coupExample.createCriteria();
        if(coupShowListBO.getName()!=null && !"".equals(coupShowListBO.getName())){
            criteria.andNameLike("%"+coupShowListBO.getName()+"%");
        }
        if(coupShowListBO.getType()!=null){
            criteria.andTypeEqualTo(coupShowListBO.getType());
        }
        if(coupShowListBO.getStatus()!=null){
            criteria.andStatusEqualTo(coupShowListBO.getStatus());
        }

        //已删除的不可见
        criteria.andDeletedEqualTo(Boolean.FALSE);

        //执行sql语句
        List<Coup> coups = coupMapper.selectByExample(coupExample);

        //获取查询总数
        PageInfo<Coup> pageInfo = new PageInfo<>(coups);
        Integer size = pageInfo.getSize();

        //以下为封装结果
        CoupUltimateShowListVO coupUltimateShowListVO = new CoupUltimateShowListVO();

        //封装进入最终结果类
        coupUltimateShowListVO.setTotal(size);
        coupUltimateShowListVO.setItems(coups);


        return coupUltimateShowListVO;

    }

    /**
     * 更新所给的数据项，返回数据库中的数据
     * @param coup
     * @return
     */
    @Override
    public Coup coupEdit(Coup coup) {

        //更新有的数据项

        //加入当前时间
        coup.setUpdateTime(new Date());

        Integer affectRows =coupMapper.updateByPrimaryKeySelective(coup);

        //返回查到的数据项
        if(affectRows!=null){
            coup = coupMapper.selectByPrimaryKey(coup.getId());
            return coup;
        }
        return null;
    }

    /**
     * 修改deleted状态以及修改更新时间
     * @param coup
     * @return
     */
    @Override
    public Integer coupDel(Coup coup) {

        Coup alterCoup = new Coup();
        alterCoup.setDeleted(Boolean.TRUE);
        alterCoup.setUpdateTime(new Date());


        CoupExample coupExample = new CoupExample();
        CoupExample.Criteria criteria = coupExample.createCriteria();
        criteria.andIdEqualTo(coup.getId());

        int affectRows = coupMapper.updateByExampleSelective(alterCoup, coupExample);


        return affectRows;
    }

    @Override
    public Coup coupCreated(Coup coup) {

        Date updateTime = new Date();
        coup.setUpdateTime(updateTime);
        coup.setAddTime(updateTime);

        Integer affectRows = coupMapper.insertSelective(coup);

        if(affectRows!=0){
            coup = coupMapper.selectByPrimaryKey(coup.getId());
            return coup;
        }
        return null;
    }


    /*----------------------------广告管理-------------------------------------*/


    /*----------------------------广告管理-------------------------------------*/

    /*----------------------------广告管理-------------------------------------*/


    /*----------------------------广告管理-------------------------------------*/


    /*----------------------------广告管理-------------------------------------*/

    /*----------------------------广告管理-------------------------------------*/

    /*----------------------------广告管理-------------------------------------*/

}
